<?php

declare (strict_types = 1);

namespace App\Service\Organziation;

use App\Constants\ErrorCode;
use App\Dao\AuthAdminLogDao;
use App\Dao\AuthRoleComponentDao;
use App\Dao\AuthRoleDao;
use App\Exception\BusinessException;
use App\Service\Auth\ModuleService;
use App\Utils\ApiUtils;
use Hyperf\DbConnection\Db;

class RoleService
{
    /**
     * 获取角色列表
     *
     * @Author czm
     * @DateTime 2020-09-28
     * @param array $params
     * @return void
     */
    function list(array $params) {

        $data = make(AuthRoleDao::class)->getIndexList($params);
        if (isset($data['count'])) {
            $count = $data['count'];
            $data = $data['data'];
        }
        return ApiUtils::send(ErrorCode::SUCCESS, "操作成功", $data ?? [], $count ?? 1);
    }

    /**
     * 获取角色功能权限信息
     *
     * @Author czm
     * @DateTime 2020-12-03
     * @param array $params
     * @return void
     */
    public function roleComponent(array $params)
    {
        //查找拥有的权限id
        $component_ids = make(AuthRoleComponentDao::class)->
            pluckByWhereTrait([['role_id', "=", $params['role_id']]], 'component_id')
            ->toArray();
        return ApiUtils::send(ErrorCode::SUCCESS, '获取成功', $component_ids);
    }

    /**
     * 添加职位
     *
     * @Author czm
     * @DateTime 2020-09-28
     * @param array $params
     * @return void
     */
    public function add(array $params)
    {
        if (make(AuthRoleDao::class)->existsByWhereTrait([['name', '=', $params['name']], ['company_id', '=', $params['company_id']]])) {
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '已存在相同角色名称');
        }
        $role = make(AuthRoleDao::class)->createTrait($params);
        make(AuthAdminLogDao::class)->addLog('新增角色' . json_encode($params, JSON_UNESCAPED_UNICODE));
        return ApiUtils::send(ErrorCode::SUCCESS, '操作成功', ['role_id' => $role->id]);
    }

    /**
     * 修改角色
     *
     * @Author czm
     * @DateTime 2020-09-28
     * @param array $params
     * @return void
     */
    public function edit(array $params)
    {
        if (make(AuthRoleDao::class)->existsByWhereTrait([['name', '=', $params['name']], ['company_id', '=', $params['company_id']], ['id', '!=', $params['role_id']]])) {
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '已存在相同角色名称');
        }
        $params['id'] = $params['role_id'];
        make(AuthRoleDao::class)->updateByIdTrait($params);
        make(AuthAdminLogDao::class)->addLog('编辑了角色信息信息' . json_encode($params, JSON_UNESCAPED_UNICODE));
        return ApiUtils::send(ErrorCode::SUCCESS, '操作成功');
    }

    /**
     * 删除角色
     *
     * @Author czm
     * @DateTime 2020-09-28
     * @param array $params
     * @return void
     */
    public function del(array $params)
    {

        Db::beginTransaction();
        try {
            $params['id'] = $params['role_id'];
            $params['is_del'] = 2;
            make(AuthRoleDao::class)->updateByIdTrait($params);
            make(AuthRoleComponentDao::class)->deleteByWhereTrait(['role_id' => $params['role_id']]);
            make(AuthAdminLogDao::class)->addLog('删除模块角色' . json_encode($params, JSON_UNESCAPED_UNICODE));
            make(ModuleService::class)->clearRedisPermission($params['role_id']);
            Db::commit();
        } catch (\Throwable $t) {
            Db::rollBack();
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '网络异常 数据写入失败');
        }
        return ApiUtils::send(ErrorCode::SUCCESS, '操作成功');
    }

    /**
     * 配置权限
     *
     * @Author czm
     * @DateTime 2020-12-03
     * @param array $params
     * @return void
     */
    public function set(array $params)
    {
        $component_ids = explode(",", $params['component_ids']);
        $component_id = make(AuthRoleComponentDao::class)->
            pluckByWhereTrait([['role_id', "=", $params['role_id']]], 'component_id')
            ->toArray();
        $addDiff = array_diff($component_ids, $component_id);
        $delDiff = array_diff($component_id, $component_ids);
        if (!empty($delDiff)) {
            make(AuthRoleComponentDao::class)->deleteByWhereAndInTrait([
                'role_id' => $params['role_id'],
            ], 'component_id', $delDiff);
        }
        if (!empty($addDiff)) {
            $insert = [];
            foreach ($addDiff as $val) {
                $insert[] = [
                    'role_id' => $params['role_id'],
                    'component_id' => $val,
                    'company_id' => $params['company_id'],
                ];
            }
            make(AuthRoleComponentDao::class)->insertTrait($insert);
        }
        make(AuthAdminLogDao::class)->addLog('编辑了模块权限' . json_encode($params, JSON_UNESCAPED_UNICODE));
        make(ModuleService::class)->clearRedisPermission($params['role_id']);
        return ApiUtils::send(ErrorCode::SUCCESS, '操作成功');

    }
}
